package com.witframework.core;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;



/**
 *该类通过：
 *<pre>
 *&lt;context-param&gt;
 *		&lt;description&gt;Spring ApplicationContext配置文件&lt;/description&gt;
 *		&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
 *		&lt;param-value&gt;classpath:classpath:/applicationcontext/applicationContext.xml&lt;/param-value&gt;
 *&lt;/context-param&gt;
 *</pre>
 *初始化WebApplicationContext实例，SpringBeanFactory通过该实例获取spring bean的实例
 *<P>
 * @author wuxinyang
 *
 */
public class ContextLoaderListener implements ServletContextListener{
	private ContextLoader contextLoader;
	private WebApplicationContext webApplicationContext=null;
	

	public void contextInitialized(ServletContextEvent event){
		webApplicationContext=(WebApplicationContext)event.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		if(webApplicationContext==null){
			this.contextLoader = new ContextLoader();
			ServletContext servletContext=event.getServletContext();
			webApplicationContext=this.contextLoader.initWebApplicationContext(servletContext);
		}
		BeanFactory.instance(webApplicationContext);
	}

	public void contextDestroyed(ServletContextEvent event) {
		if (this.contextLoader != null) {
			this.contextLoader.closeWebApplicationContext(event.getServletContext());
		}
	}

}
